<template>
  <div class="ai">
    <div @click="goToCategory(name)" class="flex" style="cursor: pointer;align-items: center;">
      <span class="cardTitle">{{name}}</span>
      <img loading="lazy" style="width: 20px;height: 20px;" src="/chevron-right.png" alt="">
    </div>
    <div ref="scrollContainer" class="content-container" @mousedown="handleMouseDown" @mousemove="handleMouseMove" @mouseup="handleMouseUp" @mouseleave="handleMouseUp">
      <div class="app-grid">
        <div v-for="(item) in list.splice(0,showItem)" class="app-grid-item">
          <AppItem @click="handleClick(item)" style="box-shadow: 0px 1px 2px 0px rgba(0, 0, 0, 0.05);" :item="item"/>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
const props = defineProps({
  name:String,
  list:{
    type:Array,
    default:()=>[]
  },
  showItem:{
    type:Number,
    default:9
  },
  isIndex:{
    type:Boolean,
    default:false
  }
})

const scrollContainer = ref(null);
const isDragging = ref(false);
const startX = ref(0);
const scrollLeft = ref(0);

const handleMouseDown = (e) => {
  isDragging.value = true;
  startX.value = e.pageX - scrollContainer.value.offsetLeft;
  scrollLeft.value = scrollContainer.value.scrollLeft;
};

const handleMouseMove = (e) => {
  if (!isDragging.value) return;
  e.preventDefault();
  const x = e.pageX - scrollContainer.value.offsetLeft;
  const walk = (x - startX.value) * 2;
  scrollContainer.value.scrollLeft = scrollLeft.value - walk;
};

const handleMouseUp = () => {
  isDragging.value = false;
};

const route = useRoute()
function transformString(str) {
  // 分割字符串为单词数组
  const words = str.split(' ');
  // 处理每个单词：首字母小写
  const processedWords = words.map(word => word.charAt(0).toLowerCase() + word.slice(1));
  // 使用短横线连接处理后的单词
  return processedWords.join('-');
}
const goToCategory = (item) => {
  
    if(props.isIndex){
      return 
    }
    const url = (route.params.hasOwnProperty('language') ?  "/" + route.params.language : '') + `/${route.fullPath.includes('/games') ? 'games' : 'apps'}/${transformString(item)}`
    navigateTo(url)
}
const handleClick = (item)=>{
    let url = (route.params.hasOwnProperty('language') ?  "/" + route.params.language : '') + `/android/${item.app_slug}`
    navigateTo(url)
}
</script>
<style scoped lang="less">
.ai{
  margin-bottom: 24px;
}

.content-container {
  user-select: none;
  overflow-x: auto;
  cursor: grab;
  scrollbar-width: none;
  -ms-overflow-style: none;

  &::-webkit-scrollbar {
    display: none;
  }

  &:active {
    cursor: grabbing;
  }

  .app-grid {
    display: grid;
    grid-template-columns: repeat(3, 1fr);
    gap: 16px;
    width: 100%;
    
    @media screen and (max-width: 768px) {
      grid-template-columns: repeat(3, 300px);
      min-width: max-content;
    }
  }

  .app-grid-item {
    width: 100%;
  }
}
</style>